﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Data.Entity;
using Service;

namespace ECommerce.Controls
{
	public partial class RelatedProducts : BaseUserControl
	{
		private IRelatedProductService _RelatedProductService;

		public int TheProductID
		{
			get
			{ 
				return CommonHelper.QueryStringInt("productid");
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				var relatedProducts = GetRelatedProducts();

				if(relatedProducts != null && relatedProducts.Count > 0)
				{
					this.RepeaterRelatedProducts.DataSource = relatedProducts;
					this.RepeaterRelatedProducts.DataBind();
				}
				else
				{
					Page.ClientScript.RegisterStartupScript(typeof(string), Guid.NewGuid().ToString(), @"<script type='text/javascript'>$('#relatedproductscontainer').css('display', 'none');</script>");
				}
			}
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			this.LRelatedProductsTitle.Text = GetLocalResourceString("RelatedProducts.Title");
		}

		protected void RepeaterRelatedProducts_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			if(e.Item.DataItem != null)
			{
				System.Web.UI.WebControls.HyperLink hl = (System.Web.UI.WebControls.HyperLink)e.Item.FindControl("HyperLinkProduct");

				hl.NavigateUrl = "~/ProductDetail.aspx?productid=" + ((Data.Entity.Product)e.Item.DataItem).ProductID;
				hl.ImageUrl = "~/PictureHandler.ashx?picturesize=130&productid=" + ((Data.Entity.Product)e.Item.DataItem).ProductID;
			}
		}

		private IList<Product> GetRelatedProducts()
		{
			if(TheProductID > 0)
			{
				if(_RelatedProductService == null)
				{
					_RelatedProductService = new RelatedProductService();
				}

				var relatedProducts = _RelatedProductService.GetRelatedProducts(TheProductID);

				if (relatedProducts == null)
				{
					return null;
				}

				var relatedProdIDs = relatedProducts.Select(exp=>exp.ProductID2);

				return _RelatedProductService.GetRelatedProducts(relatedProdIDs);

				//if(relatedProds == null || relatedProds.Count <= 0)
				//{
				//    return null;
				//}
				//else
				//{
				//    return relatedProds;
				//}
			}
			else
			{
				return null;
			}
		}
	}
}